/*
*  Copyright 2019-2023 oyun
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/package com.oyun.modules.medicine.rest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oyun.annotation.Log;
import com.oyun.config.FileProperties;
import com.oyun.modules.medicine.domain.CompanyHp;
import com.oyun.modules.medicine.domain.CompanyPicture;
import com.oyun.modules.medicine.domain.HpPicture;
import com.oyun.modules.medicine.domain.PharmaceuticalCompany;
import com.oyun.modules.medicine.domain.vo.PharmaceuticalCompanyQueryCriteria;
import com.oyun.modules.medicine.mapper.CompanyHpMapper;
import com.oyun.modules.medicine.mapper.CompanyPictureMapper;
import com.oyun.modules.medicine.service.PharmaceuticalCompanyService;
import com.oyun.utils.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
* @author oyun
* @date 2024-04-29
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "药企管理管理")
@RequestMapping("/api/pharmaceuticalCompany")
public class PharmaceuticalCompanyController {

    private final PharmaceuticalCompanyService pharmaceuticalCompanyService;

    private final FileProperties properties;

    private final CompanyPictureMapper companyPictureMapper;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('pharmaceuticalCompany:list')")
    public void exportPharmaceuticalCompany(HttpServletResponse response, PharmaceuticalCompanyQueryCriteria criteria) throws IOException {
        pharmaceuticalCompanyService.download(pharmaceuticalCompanyService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询药企管理")
    @ApiOperation("查询药企管理")
    @PreAuthorize("@el.check('pharmaceuticalCompany:list')")
    public ResponseEntity<PageResult<PharmaceuticalCompany>> queryPharmaceuticalCompany(PharmaceuticalCompanyQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(pharmaceuticalCompanyService.queryAll(criteria,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增药企管理")
    @ApiOperation("新增药企管理")
    @PreAuthorize("@el.check('pharmaceuticalCompany:add')")
    public ResponseEntity<Object> createPharmaceuticalCompany(@Validated @RequestBody PharmaceuticalCompany resources){
        pharmaceuticalCompanyService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改药企管理")
    @ApiOperation("修改药企管理")
    @PreAuthorize("@el.check('pharmaceuticalCompany:edit')")
    public ResponseEntity<Object> updatePharmaceuticalCompany(@Validated @RequestBody PharmaceuticalCompany resources){
        pharmaceuticalCompanyService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除药企管理")
    @ApiOperation("删除药企管理")
    @PreAuthorize("@el.check('pharmaceuticalCompany:del')")
    public ResponseEntity<Object> deletePharmaceuticalCompany(@RequestBody List<Long> ids) {
        pharmaceuticalCompanyService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    @ApiOperation("上传药企图片")
    @PostMapping("/uploadProcessDefinition/{companyId}")
    public ResponseEntity<Object> uploadOrUpdate(MultipartFile file, HttpServletRequest request , @PathVariable("companyId")  Long id){
        return  new ResponseEntity<>(pharmaceuticalCompanyService.uploadOrUpdate(file,request,id),HttpStatus.OK);
    }


    @ApiOperation("根据名称查询")
    @GetMapping("/getByName")
    public ResponseEntity<Object> getByUsername(@RequestParam String name) {
        return new ResponseEntity<>(pharmaceuticalCompanyService.getByName(name), HttpStatus.OK);
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("images") MultipartFile[] images, @RequestParam("companyId") Long companyId) {
        File filee = new File(properties.getPath().getPath() + "/company");
        if (!filee.exists()) {//不存在
            filee.mkdirs();
        }
        for (MultipartFile image : images) {
            String filename = image.getOriginalFilename();//获取文件名称带后缀名
            String uid = UUID.randomUUID().toString();//生成32为uuid值
            String suffix = filename.substring(filename.lastIndexOf(".")); //切割获取.后面的jpg
            String newFile = uid + suffix;//拼接新的文件名称
            File file1 = new File(filee + "/" + newFile);
            try {
                image.transferTo(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            LambdaQueryWrapper<CompanyPicture> wrapper = new LambdaQueryWrapper<>();
            CompanyPicture companyPicture = new CompanyPicture();
            companyPicture.setCompanyId(companyId);
            companyPicture.setPathImage("/company/" + newFile);
            companyPicture.setStatus(1);
            companyPictureMapper.insert(companyPicture);
        }
        return ResponseEntity.ok("图片上传成功。");
    }
}
